import { ItemStack } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { RandomUtils } from "@sapi-game/utils";
import { WereWolfTimeLimiter } from "@/werewolf/components/timeLimiter";
import { WereWolfWitchTool } from "@/werewolf/components/witchTool";
import { WereWolfModule } from "@/werewolf/module";
import { WereWolfRole, WereWolfStatus } from "@/werewolf/player";
import { WereWolfGapPhase } from "./gap";
import { WereWolfMorningPhase } from "./morning";
import { WereWolfNextTool } from "@/werewolf/components/nextTool";

export class WereWolfWitchPhase extends WereWolfModule.State {
    get witch() {
        return this.context.players.find(
            (p) => p.role == WereWolfRole.Witch && !p.dead
        );
    }

    override onEnter(): void {
        this.addComponent(Timer, {
            initialTime: this.witch ? 40 : RandomUtils.intRange(5, 15),
        })
            .addComponent(WereWolfTimeLimiter, {
                getPlayers: () => {
                    const witch = this.witch;
                    return witch ? [witch] : [];
                },
                onEnd: () => this.next(),
            })
            .addComponent(WereWolfWitchTool)
            .addComponent(WereWolfNextTool, {
                onUse: () => this.next(),
                getPlayers: () => (this.witch ? [this.witch] : []),
            });
        this.addComponents(this.context.map.phaseViews.witch);
    }

    startPhase() {
        this.getComponent(Timer).start();
        const witch = this.witch;
        if (!witch) return;
        if (this.context.poison) {
            witch.giveItem(new ItemStack("werewolf:poison"));
        }
        if (this.context.antidote) {
            witch.giveItem(new ItemStack("werewolf:antidote"));
        }
        const next = new ItemStack("werewolf:next");
        next.nameTag = "跳过";
        witch.giveItem(next);

        const killedPlayer = this.context.players.filter(
            (p) => p.status == WereWolfStatus.killed
        );
        witch.sendMessage(
            "今天晚上死的是:" + killedPlayer.map((p) => p.name).join(",")
        );
    }

    next() {
        const witch = this.witch;
        if (witch) {
            witch.clear("werewolf:poison");
            witch.clear("werewolf:antidote");
            witch.clear("werewolf:next");
        }
        this.popState();
    }
}
